package com.chaochis.wind.config.security_config;

import com.chaochis.wind.config.api.ApiCode;
import com.chaochis.wind.config.api.ApiResult;
import com.chaochis.wind.user.service.WindUserService;
import com.chaochis.wind.util.wrapper_http.WindRequestWrapper;
import com.chaochis.wind.util.wrapper_http.WindResponseWrapper;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Getter
@Setter
@Log4j2
@Repository("webAdminFilter")
public class WebAdminInterceptor implements HandlerInterceptor {

  private String loginUrl;

  @Autowired
  private WindUserService windUserService;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    log.info("url: " + this.loginUrl);
    var windRequest = new WindRequestWrapper(request);
    var windResponse = new WindResponseWrapper(response);
    var token = windRequest.getRequestToken();
    // 如果是登录接口，直接放过
    if (windRequest.getRequestURI().equals(this.loginUrl)){
      return true;
    }
    // 如果token为空的话，证明该账号还没有登录系统
    if (StringUtils.isBlank(token)) {
      var result = ApiResult.build("您还未登录系统!", false, ApiCode.NotLogin, null);
      windResponse.setReturnResult(result);
      return false;
    }
    // 从redis里面取
    var windUser = this.windUserService.getTempUserInfoByToken(token);
    if (windUser == null) {
      var result = ApiResult.build("您的账号已过期,请重新登录", false, ApiCode.TokenExpired, null);
      windResponse.setReturnResult(result);
      return false;
    } else {
      var userStatus = windUser.getUserStatus();
    }
    return true;
  }

  /**
   * 判断是不是登录请求
   * @param request
   * @return
   */
  private boolean isLoginUrl(HttpServletRequest request) {
      return request.getRequestURI().equals(this.loginUrl);
  }
}
